package net.youdi.gateway.handler.request;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import net.youdi.gateway.context.KeyStore;
import net.youdi.gateway.properties.GatewayProperties;
import net.youdi.gateway.util.GateWayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.nio.charset.StandardCharsets;

/**
 * @author: scl
 * @date: 2020-07-23 17:08
 * @description 对请求数据解密处理器
 */
@Component
@Order(Integer.MIN_VALUE)
public class DecryptRequestBodyHandler implements RequestBodyHandler {

    @Override
    public String handler(ServerWebExchange exchange, String data) {
        String userAgent = exchange.getRequest().getHeaders().getFirst("user-agent");
        String bodyHandle = exchange.getRequest().getHeaders().getFirst("bodyHandle");
        if (userAgent != null && bodyHandle != null){
            if (GateWayUtil.isWeb(userAgent)){
                return decryptWeb(data);
            }
            if (GateWayUtil.isAndroid(userAgent)){
                return decryptAndroid(data);
            }
            if (GateWayUtil.isIos(userAgent)){
                return decryptIos(data);
            }
        }
        return data;
    }

    private String decryptIos(String data) {
        data = data.replace(" ", "");
        data = StrUtil.subBetween(data,"rsaSign\":\"","}");
        byte[] decrypt = KeyStore.iosRsa.decrypt(Base64.decode(data), KeyType.PrivateKey);
        return new String(decrypt,StandardCharsets.UTF_8);
    }

    private String decryptAndroid(String data) {
        byte[] decrypt = KeyStore.androidRsa.decrypt(HexUtil.decodeHex(data), KeyType.PrivateKey);
        return new String(decrypt,StandardCharsets.UTF_8);
    }

    private String decryptWeb(String data) {
       /* data = data.replace(" ", "");
        data = StrUtil.subBetween(data,"rsaSign\":\"","}");
        byte[] decrypt = KeyStore.webRsa.decrypt(Base64.decode(data), KeyType.PrivateKey);
        return new String(decrypt,StandardCharsets.UTF_8);*/
        return data;
    }
}
